package cn.kgc.boot.vue.controller;

import cn.hutool.crypto.SecureUtil;
import cn.kgc.boot.vue.entity.User;
import cn.kgc.boot.vue.form.LoginForm;
import cn.kgc.boot.vue.response.ResponseResult;
import cn.kgc.boot.vue.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 课工场
 * @date 2025/9/9
 * @description 用户模块的控制层  和用户相关的请求全部有该类进行处理
 * http请求
 */
@RestController   // 组合注解     @Controller  @ResponseBody  声明返回的数据类型是json格式
@RequestMapping("user")   // 请求映射
@CrossOrigin    // 允许跨域请求
public class UserController {

    // 注入业务层
    @Resource
    private UserService userService;

    // 处理查询用户列表的请求     /user/list
    @RequestMapping("list")
    public ResponseResult userList() {
        List<User> list = userService.list();
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setData(list);
        responseResult.setMessage("查询成功");
        return responseResult;
    }

    //  /user/addOrUpdate        axios post     json
    @RequestMapping("addOrUpdate")
    public ResponseResult addOrUpdateUser(@RequestBody User user) {
        // 新增  编辑   新增 id=""  编辑  id=1
        Integer id = user.getId();
        if (id == null) {  // 新增
            // 默认密码
            String defaultPwd = "111111";
            // MD5 摘要算法
            String md5PWD = SecureUtil.md5(defaultPwd);
            user.setPassword(md5PWD);
        }
        // 在数据库层面会自动检测用户名的唯一性   id  是否为null
        ResponseResult responseResult = new ResponseResult();
        try {
            userService.saveOrUpdate(user);
            responseResult.setCode(200);
            responseResult.setMessage("操作成功");
        } catch (Exception e) {
            responseResult.setCode(500);
            responseResult.setMessage("数据库字段重复,请检查...");
        }
        return responseResult;
    }


    @RequestMapping("page")
    public ResponseResult userPage(Integer page, Integer size) {
        System.out.println("page = " + page + ", size = " + size);
        // 分页查询    创建分页对象
        Page<User> userPage = new Page<>(page, size);
        Page<User> page1 = userService.page(userPage, null);

        // total   data
        Long total = page1.getTotal();
        List<User> records = page1.getRecords();

        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setData(records);
        responseResult.setCount(total);
        return responseResult;
    }

    // 批量删除
    @RequestMapping("delete")
    public ResponseResult deleteUser(String ids) {

        String[] split = ids.split(",");
        ArrayList<Integer> delIds = new ArrayList<>();
        for (String id : split) {
            delIds.add(Integer.valueOf(id));
        }
        // 批量删除
        userService.removeByIds(delIds);

        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setMessage("删除成功");
        return responseResult;
    }

    // 删除一条数据
    @RequestMapping("remove")
    public ResponseResult deleteUser(Integer id) {
        ResponseResult responseResult = new ResponseResult();
        try {
            userService.removeById(id);
            responseResult.setCode(200);
            responseResult.setMessage("删除成功");
        } catch (Exception e) {
            responseResult.setCode(500);
            responseResult.setMessage("删除失败");
        }
        return responseResult;
    }


    @RequestMapping("register")
    public ResponseResult registerUser(@RequestBody User user) {
        // 1. 判定用户名是否存在
        String username = user.getUsername();
        // 查询条件对象
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);

        User one = userService.getOne(userQueryWrapper);
        ResponseResult responseResult = new ResponseResult();
        if (ObjectUtils.isNotNull(one)) {
            responseResult.setCode(110);
            responseResult.setMessage("用户名已存在");
            return responseResult;
        }

        // 2. 密码加密   123456
        String password = user.getPassword();
        String md5PWD = SecureUtil.md5(password);
        user.setPassword(md5PWD);

        // 3. 添加数据到数据库
        try {
            userService.save(user);
            responseResult.setCode(200);
            responseResult.setMessage("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setCode(500);
            responseResult.setMessage("注册失败");
        }
        // 4. 响应结果
        return responseResult;
    }


    @RequestMapping("login")
    public ResponseResult login(@RequestBody LoginForm userForm) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", userForm.getUsername())
                .eq("password", SecureUtil.md5(userForm.getPassword()));

        User one = userService.getOne(userQueryWrapper);
        // 判定 认证是否通过
        ResponseResult responseResult = new ResponseResult();
        if (ObjectUtils.isNotNull(one)) {
            responseResult.setCode(200);
            responseResult.setMessage("认证通过");
            return responseResult;
        }

        responseResult.setCode(110);
        responseResult.setMessage("用户名或密码错误");
        return responseResult;

    }


}
